import requests,random,json
import demjson
from pyquery import PyQuery as pq
from com.lechebang.Setting import *


def parse(brandData):
    brands=[]
    for key, v in brandData.items():
        # print("====>" + key)
        for item in v:
            brand={}
            brand['id']=item['id']
            brand['name']=item['name']
            brand['index']=key
            brand['url']= item['url']
            brand['cur']= item['cur']
            brand['num']= item['num']
            # print(brand)
            brands.append(brand)
    # print(brands)
    return brands


def get_brand():
    url=URL_BRAND % ('jiangsu')
    headersData=get_headers()
    if(headersData==None):
        print("====>request init error!!!!!")
        return

    result=requests.get(url,headers=headersData)
    if result.status_code==200:
        tmp=result.text
        # print(content)
        print(tmp.find("{"))
        content=tmp[tmp.find("{"):-1]
        brands=demjson.decode(content,"utf-8")
        brandData=brands['brand']
        result=parse(brandData)
        return result
    else:
        return None


def get_headers():
    ua = random.choice(USER_AGENT_LIST)
    if ua:
        headers={}
        headers['User-Agent']=ua
        return headers
    return None


if __name__ == '__main__':
    get_brand()